#!/usr/bin/env python

import csv
import os
import sys


basePath = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))

sys.path.append(os.path.join(basePath,'modules'))
import mods

cursor = mods.GetDBConnection().cursor()
exportDir = os.path.join(basePath, 'www', 'download')
if not os.path.isdir(exportDir):
	sys.exit("%s does not exist" % (exportDir))


def PublicHolidays():
	csvFile = os.path.join(exportDir, 'public-holidays.csv')

	csvWriter = csv.writer(open(csvFile, "w"))

	cursor.execute("""SELECT holiday_date, non_working_day, holiday FROM public_holidays ORDER BY holiday_date""")
	for record in cursor.fetchall():
		(holidayDate, nonWorkingDay, holiday) = record
		csvWriter.writerow((holidayDate, nonWorkingDay, holiday))


def Locations():
	csvFile = os.path.join(exportDir, 'locations.csv')

	csvWriter = csv.writer(open(csvFile, "w"))

	cursor.execute("""SELECT id, parent, postal_code_street, postal_code_box, afr_name, eng_name, nso_name, sot_name, nbl_name, ssw_name, tso_name, tsn_name, ven_name, xho_name, zul_name FROM locations ORDER BY eng_name""")
	for record in cursor.fetchall():
		csvWriter.writerow(record)



def PostgresSQL():
	pgDir = os.path.join(exportDir, 'pg')
	if not os.path.isdir(pgDir):
		sys.exit("%s does not exist" % (pgDir))

	os.system("""pg_dump --no-owner --table=locations --file=%s %s""" % (os.path.join(pgDir, 'locations.sql'), mods.dbName))
	os.system("""pg_dump --no-owner --table=location_todo --file=%s %s""" % (os.path.join(pgDir, 'location_todo.sql'), mods.dbName))
	os.system("""pg_dump --no-owner --table=public_holidays --file=%s %s""" % (os.path.join(pgDir, 'public_holidays.sql'), mods.dbName))
	os.system("""pg_dump --no-owner --table=db_version --file=%s %s""" % (os.path.join(pgDir, 'db_version.sql'), mods.dbName))
	os.system("""pg_dump --no-owner --table=tickets --file=%s %s""" % (os.path.join(pgDir, 'tickets.sql'), mods.dbName))
	
	os.system("""pg_dump --schema-only --no-owner --table=oid_associations --file=%s %s""" % (os.path.join(pgDir, 'oid_associations.sql'), mods.dbName))
	os.system("""pg_dump --schema-only --no-owner --table=oid_nonces --file=%s %s""" % (os.path.join(pgDir, 'oid_nonces.sql'), mods.dbName))
	os.system("""pg_dump --schema-only --no-owner --table=user_log --file=%s %s""" % (os.path.join(pgDir, 'user_log.sql'), mods.dbName))
	os.system("""pg_dump --schema-only --no-owner --table=users --file=%s %s""" % (os.path.join(pgDir, 'users.sql'), mods.dbName))



if __name__ == "__main__":
	PublicHolidays()
	Locations()
	PostgresSQL()

